package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/gogf/gf/v2/frame/g"
)

func main() {
	// Update()
	Select()
}

func Select() {
	v := g.Client().GetVar(context.Background(), "http://localhost:8881/restful/gf_test1", g.Map{
		"page": 1,
		"size": 5,
		// "fields":  "test_name",
		"orderby": "id desc",
	})
	fmt.Println(v)
	// {"list":[{"id":1,"test_id":"123","test_name":"测试123"}],"page":1,"size":10,"total":1,"totalPage":1}
}

func SelectById() {
	v := g.Client().GetVar(context.Background(), "http://localhost:8881/restful/gf_test1/3")
	fmt.Println(v)
	// {"id":1,"test_id":"123","test_name":"测试123"}
}

func Insert() {
	resp, err := g.Client().Post(context.Background(), "http://localhost:8881/restful/gf_test1",
		`{"test_id":"44","test_name":"测试44"}`)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.Response.StatusCode == http.StatusCreated {
		fmt.Println("创建成功")
	} else {
		fmt.Println("创建失败")
		fmt.Println(resp.Response.StatusCode)
		bs, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}
		fmt.Println(string(bs))
	}
}

func Delete() {
	resp, err := g.Client().Delete(context.Background(), "http://localhost:8881/restful/gf_test1/2")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.Response.StatusCode == http.StatusNoContent {
		fmt.Println("删除成功")
	} else {
		fmt.Println("删除失败")
		fmt.Println(resp.Response.StatusCode)
		bs, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}
		fmt.Println(string(bs))
	}
}

func Update() {
	resp, err := g.Client().Put(context.Background(), "http://localhost:8881/restful/gf_test1/3",
		`{"test_id":"442222","test_name":"测试442222"}`)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.Response.StatusCode == http.StatusOK {
		fmt.Println("更新成功")
	} else {
		fmt.Println("更新失败")
		fmt.Println(resp.Response.StatusCode)
		bs, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}
		fmt.Println(string(bs))
	}
}
